package com.example.star.controller;

import com.example.star.entity.User;
import com.example.star.entity.UserRole;
import com.example.star.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import java.math.BigDecimal;
import java.util.*;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @ResponseBody
    @GetMapping("/users/normal")
    public List<User> getNormalUsers() {
        return userService.getNormalUsers();
    }

    @ResponseBody
    @GetMapping("/users/admin")
    public List<User> getAdminUsers() {
        return userService.getAdminUsers();
    }
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    // 显示登录页面
    @GetMapping("/login")
    public String showLoginPage() {
        return "login";
    }

    /// 处理登录请求
    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        // 校验用户名和密码是否为空
        if (!validateLoginParams(username, password)) {
            response.put("success", false);
            response.put("message", "用户名和密码不能为空");
            logger.info("登录失败：用户名和密码不能为空，用户名：{}，IP地址：{}", username, request.getRemoteAddr());
            return response;
        }

        try {
            Optional<User> userOptional = userService.login(username, password);
            if (userOptional.isPresent()) {
                User user = userOptional.get();
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                response.put("success", true);
                response.put("message", "登录成功");
                response.put("role", user.getRole());
                logger.info("用户登录成功，用户名：{}，角色：{}，IP地址：{}", username, user.getRole(), request.getRemoteAddr());
            } else {
                response.put("success", false);
                response.put("message", "用户名或密码错误");
                logger.info("登录失败：用户名或密码错误，用户名：{}，IP地址：{}", username, request.getRemoteAddr());
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "登录过程中出现错误，请稍后再试");
            logger.error("登录失败：出现异常，用户名：{}，IP地址：{}，异常信息：{}", username, request.getRemoteAddr(), e.getMessage());
        }

        return response;
    }

    // 校验登录参数
    private boolean validateLoginParams(String username, String password) {
        return StringUtils.hasText(username) && StringUtils.hasText(password);
    }

    // 显示注册页面
    @GetMapping("/register")
    public String showRegisterPage() {
        return "register";
    }

    // 处理注册请求
    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(@RequestParam("username") String username, @RequestParam("nickname") String nickname, @RequestParam("password") String password,
                                        @RequestParam(required = false) String repassword) {
        Map<String, Object> response = new HashMap<>();
        // 校验用户名和密码是否为空
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            response.put("success", false);
            response.put("message", "用户名和密码不能为空");
            logger.info("注册失败：用户名和密码不能为空，用户名：{}", username);
            return response;
        }
        // 校验昵称是否为空
        if (!StringUtils.hasText(nickname)) {
            response.put("success", false);
            response.put("message", "昵称不能为空");
            logger.info("注册失败：昵称不能为空，昵称：{}", nickname);
            return response;
        }
        if (repassword != null && !password.equals(repassword)) {
            response.put("success", false);
            response.put("message", "密码和确认密码不一致");
            logger.info("注册失败：密码和确认密码不一致，用户名：{}", username);
            return response;
        }
        // 校验用户名是否已存在
        if (userService.isUsernameExists(username)) {
            response.put("success", false);
            response.put("message", "用户名已存在，请选择其他用户名");
            logger.info("注册失败：用户名已存在，用户名：{}", username);
            return response;
        }
        // 校验昵称是否已存在
        if (userService.isNicknameExists(nickname)) {
            response.put("success", false);
            response.put("message", "昵称已存在，请选择其他昵称");
            logger.info("注册失败：昵称已存在，昵称：{}", nickname);
            return response;
        }
        User user = new User(username, nickname, password);
        // 根据用户名是否以 "MR" 开头来设置角色
        if (username.startsWith("MR")) {
            user.setRole(UserRole.ADMIN.name());
        } else {
            user.setRole(UserRole.USER.name());
        }
        userService.register(user);
        response.put("success", true);
        response.put("message", "注册成功");
        logger.info("用户注册成功，用户名：{}，角色：{}", username, user.getRole());
        return response;
    }

    // 显示主页
    @GetMapping("/home")
    public String showHomePage() {
        return "home";
    }

    // 显示用户管理页面
    @GetMapping("/userlist")
    public String showUserListPage(Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        if (userService.isAdmin(user)) {
            model.addAttribute("users", userService.getAllUsers());
        } else {
            List<User> users = new ArrayList<>();
            users.add(user);
            model.addAttribute("users", users);
        }
        model.addAttribute("currentUser", user);
        return "userlist";
    }
  //处理删除请求
    @PostMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") Integer id, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            return "redirect:/login";
        }
        // 特殊处理 MR1002 用户
        if ("MR1002".equals(currentUser.getUsername())) {
            Optional<User> userToDeleteOptional = userService.findUserById(id);
            if (userToDeleteOptional.isPresent()) {
                User userToDelete = userToDeleteOptional.get();
                // 即使是管理员也能被 MR1002 删除
                userService.deleteUserById(id);
                logger.info("用户 MR1002 删除了用户，ID: {}, 用户名: {}", id, userToDelete.getUsername());
            }
            return "redirect:/userlist";
        }
        // 普通管理员权限逻辑
        if (!userService.isAdmin(currentUser)) {
            return "redirect:/login";
        }
        if (currentUser.getId().equals(id)) {
            logger.info("不能删除自己，用户 ID：{}", id);
            return "redirect:/userlist";
        }
        Optional<User> userToDeleteOptional = userService.findUserById(id);
        if (userToDeleteOptional.isPresent()) {
            User userToDelete = userToDeleteOptional.get();
            if (userService.isAdmin(userToDelete)) {
                logger.info("普通管理员不能删除其他管理员，用户 ID：{}", id);
                return "redirect:/userlist";
            }
            userService.deleteUserById(id);
            logger.info("普通管理员删除了普通用户，用户 ID：{}", id);
        }
        return "redirect:/userlist";
    }

    // 显示用户编辑页面
    @GetMapping("/editUser/{id}")
    public String showEditUserPage(@PathVariable("id") Integer id, Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        if (!userService.isAdmin(user) && !user.getId().equals(id)) {
            return "redirect:/userlist";
        }
        Optional<User> userOptional = userService.findUserById(id);
        if (userOptional.isPresent()) {
            model.addAttribute("user", userOptional.get());
            model.addAttribute("currentUser", user);
            return "editUser";
        }
        return "redirect:/userlist";
    }

    // 处理用户编辑请求
    @PostMapping("/editUser")
    public String editUser(@ModelAttribute User user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            return "redirect:/login";
        }

        // 检查是否为特殊用户名“MR1002”
        Optional<User> targetUserOptional = userService.findUserById(user.getId());
        if (targetUserOptional.isPresent()) {
            User targetUser = targetUserOptional.get();
            if ("MR1002".equals(targetUser.getUsername())) {
                return "redirect:/userlist";
            }

            // 检查是否为管理者之间互相编辑
            if (userService.isAdmin(currentUser) && userService.isAdmin(targetUser) && !currentUser.getId().equals(targetUser.getId())) {
                return "redirect:/userlist";
            }
        }

        if (!userService.isAdmin(currentUser) && !currentUser.getId().equals(user.getId())) {
            return "redirect:/userlist";
        }

        Optional<User> originalUserOptional = userService.findUserById(user.getId());
        if (originalUserOptional.isPresent()) {
            User originalUser = originalUserOptional.get();
            user.setRole(originalUser.getRole());
            // 如果密码为空，使用原密码
            if (!StringUtils.hasText(user.getPassword())) {
                user.setPassword(originalUser.getPassword());
            }
        }
        userService.updateUser(user);
        logger.info("用户信息更新成功，用户 ID：{}", user.getId());
        return "redirect:/userlist";
    }

    @RequestMapping("/api/users")
    @GetMapping("/{id}")
    public Optional<User> getUserById(@PathVariable Integer id) {
        return userService.findUserById(id);
    }

    @ResponseBody
    @GetMapping("/users_by_username")
    public User getUserByUsername(@RequestParam("username") String username) {
        return userService.getUserByUsername(username);
    }

    @ResponseBody
    @PutMapping("/update_by_username")
    public ResponseEntity<User> updateUserByUsername(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("nickname") String nickname) {

        User updatedUser = userService.updateUserByUsername(username, password, nickname);
        return ResponseEntity.ok(updatedUser);
    }

    @ResponseBody
    @PutMapping("/update/avatar")
    public ResponseEntity<User> updateAvatar(@RequestParam("username") String username,
                                             @RequestParam("avatar") String avatar) {
        User updatedUser = userService.changeUserAvatar(username, avatar);
        return ResponseEntity.ok(updatedUser);
    }
    @ResponseBody
    @PutMapping("/update/password")
    public ResponseEntity<User> changeUserPassword(@RequestParam("username") String username,@RequestParam("oldPassword") String oldPassword,
                                             @RequestParam("newPassword") String newPassword) {
        User updatedUser = userService.changeUserPassword(username, newPassword);
        return ResponseEntity.ok(updatedUser);
    }

    @ResponseBody
    @PostMapping("/update/recharge")
    public String recharge(@RequestParam("username") String username, @RequestParam("amount") double amount) {
        if (userService.recharge(username, amount)) {
            return "充值成功";
        } else {
            return "充值失败";
        }
    }

    @ResponseBody
    @PostMapping("/pay")
    public User pay(@RequestParam("username") String username, @RequestParam("money") BigDecimal money) {
        return userService.pay(username, money);
    }
    // 新增的检测用户金钱的接口
    @ResponseBody
    @PostMapping("/checkMoney")
    public BigDecimal checkMoney(@RequestParam String username) {
        return userService.checkMoney(username);
    }

}